package com.langsin.blog.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateUtils {
    public static Session getSession(){
        /*配置*/
        //1.配置类型安全的准服务注册类
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
        //2.根据服务注册类创建一个元数据资源集，同时构建元数据并生成唯一的Session工厂
        SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
        /*操作*/
        Session session = sessionFactory.openSession();
        return session;
    }

    public static void closeSession(Session session){
        if(session != null){
            if(session.isOpen()){
                session.close();
            }
        }
    }
}
